import { Search, Select } from '@alifd/next';
import { AutoCompleteProps, SelectProps } from '@alifd/next/types/select';
import React, { useEffect, useState } from 'react';

const { AutoComplete } = Select;

interface DataSelectProps extends SelectProps {
  /**
   * 查询回调
   * 传入的实现中，执行具体的接口调用
   * @param page
   * @param args
   * @returns
   */
  onFetch: (page: number, args?: any) => Promise<any>;
  /**
   * 可设置查询参数，触发重绘; args会被传递到onFetch作为入口参数
   */
  args: any;
  labelField: string;
  valueField: string;
  mapper: (obj: any) => any;
}


/**
 * 输入远程获取数据
 * @returns
 */
function DataAutoComplete({ onFetch, args, labelField, valueField, value, onChange, mapper, ...props }: DataSelectProps) {
  const [data, setData] = useState([]);
  const [_, setPage] = useState(0);
  const [loading, setLoading] = useState(false);

  const _mapper = (item: any) => ({
    label: item[labelField],
    value: item[valueField],
    item,
  });

  useEffect(() => {
    fetch(0, args);
  }, [args]);

  const handleSearch = (v: string): void => {
    if (!v) {
      setData([]);
      return;
    }
    fetch(0, { ...args, keyword: v });
  }

  async function fetch(p: number, args?: any) {
    try {
      setLoading(true);
      let res = await onFetch(p, args);
      if (p > 0 && !res?.length) return;
      if (labelField) res = res.map(_mapper);
      if (mapper) res = res.map(mapper);

      setData(p === 0 ? res : data.concat(res));
      setPage(p);
    } finally {
      setLoading(false);
    }
  }

  return (
    <Select
      showSearch
      style={{ width: '100%' }}
      filterLocal={false}
      // menuProps={{ onScroll: handleScroll }}
      dataSource={data}
      // useDetailValue
      onSearch={handleSearch}
      value={value}
      state={loading ? 'loading' : undefined}
      onChange={onChange}
      // onVisibleChange={handleVisibleChange}
      {...props}
    />
  );
}

export default DataAutoComplete;
